package xyz.xiaomuyu.moment_read_app.Fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import xyz.xiaomuyu.moment_read_app.R;
import xyz.xiaomuyu.moment_read_app.activity.CollectionForMusic;
import xyz.xiaomuyu.moment_read_app.activity.CollectionForRead;
import xyz.xiaomuyu.moment_read_app.activity.CollectionForSheying;
import xyz.xiaomuyu.moment_read_app.activity.PersonalSetting;
import xyz.xiaomuyu.moment_read_app.bean.woshishabi;
import xyz.xiaomuyu.moment_read_app.ui.clockIn.ClockInActivity;
import xyz.xiaomuyu.moment_read_app.ui.clockIn.SignCalendarReq;
import xyz.xiaomuyu.moment_read_app.util.DBUtil;
import xyz.xiaomuyu.moment_read_app.util.ImgUtil;
import xyz.xiaomuyu.moment_read_app.widget.ItemGroup;

import static java.lang.Thread.sleep;

public class PersonalFragment extends Fragment {


    private ImageView touxiang;

    private TextView nameTv;
    private ItemGroup wodeSetting;
    private View shoucang_yinyue;
    private View shoucang_sheying;
    private View shoucang_yuedu;
    View view;
    private ImageView clockIn;
    private TextView tv_current_day;
    String userName = woshishabi.userName;
    private ItemGroup yvbixitong;

    /**
     * 查询当前userName的打卡日期
     *
     * @return
     */
    public List<Date> getSignDays() {
        List<Date> signs = new ArrayList<>();
        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //线程间的沟通准备
                try {
                    Message message = new Message();
                    Connection connection = DBUtil.getConn();
                    Statement statement = connection.createStatement();
                    String query = "select clock_time from clock where user_name = '" + userName + "';";
                    ResultSet resultSet = statement.executeQuery(query);
                    while (resultSet.next()) {
                        Date date = resultSet.getDate("clock_time");
                        signs.add(date);
                    }
                    resultSet.close();
                    statement.close();
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return signs;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //不同的Activity对应不同的布局
        //view = inflater.inflate(R.layout.fragment_personal, container, false);

        final Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                view = inflater.inflate(R.layout.fragment_personal, container, false);
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //更新用户名
        String userName = getActivity().getIntent().getStringExtra("userName");
        nameTv = view.findViewById(R.id.wode_name);
        nameTv.setText(userName);

        //更新头像
        touxiang = view.findViewById(R.id.touxiang);
        String base64 = getActivity().getIntent().getStringExtra("headId");
        Bitmap bitmap = null;
        byte[] bitmapArray;
        bitmapArray = Base64.decode(base64, Base64.DEFAULT);
        bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        touxiang.setImageBitmap(bitmap);

        /**
         * 打卡功能
         */

        // 更新日历logo当前日期
        Integer d = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
        tv_current_day = view.findViewById(R.id.tv_current_day);
        tv_current_day.setText(d.toString());
        clockIn = view.findViewById(R.id.ib_calendar);
        clockIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ClockInActivity.class);
                SignCalendarReq signCalendarReq = new SignCalendarReq();
                SignCalendarReq.DataBean data = new SignCalendarReq.DataBean();
                SignCalendarReq.StateBean state = new SignCalendarReq.StateBean();

                data.setUid(userName);
                Calendar cur = Calendar.getInstance();
                data.setConSign(cur.getActualMaximum(Calendar.DAY_OF_MONTH));
                List<Date> signDays = getSignDays();
                data.setIsSign(signDays.size());
                String s = new String();
                Date now = new Date();
                Calendar today = Calendar.getInstance();
                today.setTime(now);
                for (Date date : signDays) {
                    Calendar c = Calendar.getInstance();
                    c.setTime(date);
                    s += (c.get(Calendar.DAY_OF_MONTH));
                    s += ",";
                    if (c.get(Calendar.YEAR) == today.get(Calendar.YEAR) &&
                            c.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
                        data.setIsSign(1);
                    }
                }
                data.setSignDay(s);
                state.setCode(1);
                state.setMsg("成功");

                signCalendarReq.setData(data);
                signCalendarReq.setState(state);


                intent.putExtra("userInfos", signCalendarReq);
                startActivity(intent);
            }
        });

        //进入设置界面
        wodeSetting = view.findViewById(R.id.wode_setting);
        wodeSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), PersonalSetting.class);
                startActivity(intent);
            }
        });
        //我的收藏-音乐
        shoucang_yinyue = view.findViewById(R.id.shoucang_yinue);
        shoucang_yinyue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CollectionForMusic.class);
                startActivity(intent);
            }
        });
        //我的收藏-摄影
        shoucang_sheying = view.findViewById(R.id.shoucang_sheying);
        shoucang_sheying.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CollectionForSheying.class);
                startActivity(intent);
            }
        });
        //我的收藏-阅读
        shoucang_yuedu = view.findViewById(R.id.shoucang_yuedu);
        shoucang_yuedu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CollectionForRead.class);
                startActivity(intent);
            }
        });
        //鱼币系统
        yvbixitong = view.findViewById(R.id.yvbixitong);
        int[] fish_coin = new int[1];
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                //线程间的沟通准备
                try {
                    String userName = getActivity().getIntent().getStringExtra("userName");
                    Connection connection = DBUtil.getConn();
                    Statement statement = connection.createStatement();



                    String sql = "select fish_coin from user where user_name = '" + userName +"';";


                    ResultSet resultSet = statement.executeQuery(sql);
                    String ss = null;
                    while (!resultSet.next()) {
                        fish_coin[0] = resultSet.getInt("fish_coin");
                    }
                    resultSet.close();
                    statement.close();
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        yvbixitong.setCount(String.valueOf(fish_coin[0]));

        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /* *
         * TODO 实现底部菜单对应布局控件事件
         * */

    }


    @Override
    public void onStart() {
        super.onStart();
        if (woshishabi.bitmap != null) {

            Bitmap bitmap1 = woshishabi.bitmap;
            touxiang.setImageBitmap(woshishabi.bitmap);


            //把图片写回数据库
            final Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //线程间的沟通准备
                    try {
                        String userName = getActivity().getIntent().getStringExtra("userName");
                        Connection connection = DBUtil.getConn();
                        Statement statement = connection.createStatement();

                        String newPhoto = ImgUtil.bitmapToBase64(bitmap1);
                        Log.d("result", newPhoto);
                        String sql = "update user set head_id = " + "'" + newPhoto + "'"
                                + "where user_name = " + "'" + userName + "';";
                        statement.executeUpdate(sql);

                        String query = "select head_id from user where user_name = 'xiaomuyu'";
                        ResultSet resultSet = statement.executeQuery(query);
                        String ss = null;
                        while (!resultSet.next()) {
                            ss = resultSet.getString("head_id");
                        }
                        resultSet.close();
                        statement.close();
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
